<template>
  <div class="accountContainer">
    <el-card>
      <el-row>
        <el-col :span="6">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="search"
            clearable
            @change="searchClick"
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="searchClick"
            >搜索用户</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="danger" icon="el-icon-delete" @click="batchDelete"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="" icon="el-icon-plus" @click="addAccount"
            >用户添加</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-row :gutter="10">
        <!-- 表格 -->
        <el-table :data="user" style="width: 100%" ref="table">
          <!-- 多选 -->
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="userId" label="用户学/工号" width="200">
          </el-table-column>
          <el-table-column prop="userName" label="用户姓名"> </el-table-column>
          <el-table-column prop="userIdentity" label="用户身份">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.userIdentity == '0'">学生</el-tag>
              <el-tag v-else-if="scope.row.userIdentity == '1'" type="warning"
                >老师</el-tag
              >
              <el-tag v-else-if="scope.row.userIdentity == '3'" type="success"
                >管理员</el-tag
              >
              <el-tag v-else type="error">未知身份</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userMobile" label="手机号"> </el-table-column>
          <el-table-column prop="userGender" label="用户性别">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.userGender == '0'" type="warning"
                >女</el-tag
              >
              <el-tag v-else-if="scope.row.userGender == '1'">男</el-tag>
              <el-tag v-else type="danger">未知</el-tag>
            </template>
          </el-table-column>
          <!-- 操作区 -->
          <el-table-column label="操作">
            <!-- 插槽 slot-scope="scope"-->
            <template slot-scope="scope">
              <el-button
                type=""
                size="small"
                @click="accountEdit(scope)"
                :disabled="scope.row.userIdentity == '3' ? true : false"
                >编辑</el-button
              >
              
              <el-button
                type="danger"
                size="small"
                @click="deleteConfirm(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页 -->
      <!-- 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
       -->
      <el-row :gutter="10">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[8, 16, 24, 32]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="parseInt(totalNumber)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handleCurrentChange"
          @next-click="handleCurrentChange"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <!-- Form表单区域 -->
      <el-form :model="userForm" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="学/工号" prop="userId">
          <el-input
            v-model="userForm.userId"
            :disabled="dialogTitle == '用户编辑' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input
            v-model="userForm.userName"
            :disabled="dialogTitle == '用户编辑' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="userPassword">
          <el-input
            v-model="userForm.userPassword"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="userIdentityNumber">
          <el-input
            v-model="userForm.userIdentityNumber"
            :disabled="dialogTitle == '用户编辑' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户身份" prop="userIdentity">
          <el-radio-group
            v-model="userForm.userIdentity"
          >
            <el-radio :label="0">学生</el-radio>
            <el-radio :label="1">老师</el-radio>
            <!-- <el-radio :label="3">管理员</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="userMobile">
          <el-input
            type="text"
            v-model="userForm.userMobile"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="userGender">
          <el-radio-group v-model="userForm.userGender" @change="orderNoChange">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "Account",
  data() {
    return {
      currentPage: "",
      pageSize: "",
      totalNumber: "",
      search: "",
      // 表格用户信息
      user: [],
      //   form数据
      userForm: {
        userId: "",
        userName: "",
        userPassword: "",
        userIdentityNumber: "",
        userGender: "",
        userMobile: "",
        userIdentity: "",
      },
      //  表单选项
      dialogTitle: "",
      dialogVisible: false,
      rules: {
        userPassword: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        userIdentity: [
          {
            required: true,
            message: "请选择身份",
            trigger: "blur",
          },
        ],
        userMobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: "注意手机号格式",
            trigger: "blur",
          },
        ],
        userGender: [
          {
            required: true,
            message: "请选择性别",
            trigger: "blur",
          },
        ],
        userIdentityNumber: [
          {
            required: true,
            message: "请输入身份证号",
            trigger: "blur",
          },
          // {
          //   pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          //   message: "身份证格式错误",
          //   trigger: "blur",
          // }
        ],
        userName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        userId: [
          {
            required: true,
            message: "请输入学/工号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.currentPage = 1;
    this.pageSize = 8;
    (this.search = ""),
      this.getUserData(this.currentPage, this.pageSize, this.search);
  },
  methods: {
    orderNoChange() {
      this.$forceUpdate();
    },
    // 获取全部数据
    async getUserData(currentPage, pageSize, search) {
      this.user = [];
      const { data: res } = await axios({
        method: "GET",
        url: `/api/admin/getUserData/${currentPage}/${pageSize}`,
        params: {
          query: search,
        },
      });
      console.log(res);
      if (res.code == 200) {
        // 数据赋值
        for (let i = 0; i < res.data.list.length; i++) {
          var item = {};
          item.userGender = res.data.list[i].userGender;
          item.userId = res.data.list[i].userId;
          item.userIdentity = res.data.list[i].userIdentity;
          item.userIdentityNumber = res.data.list[i].userIdentityNumber;
          item.userMobile = res.data.list[i].userMobile;
          item.userPassword = res.data.list[i].userPassword;
          item.userName = res.data.list[i].userName;
          this.user.push(item);
        }
        // 页码赋值
        this.currentPage = res.data.pages;
        this.pageSize = res.data.pageSize;
        this.totalNumber = res.data.total;
      } else {
        this.$message.error("服务器错误，获取数据失败");
      }
    },
    // 显示条数更新
    handleSizeChange(e) {
      this.currentPage = 1;
      this.pageSize = e;
      this.getUserData(this.currentPage, this.pageSize, this.search);
    },
    // 页码更新
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getUserData(this.currentPage, this.pageSize, this.search);
    },
    // 点击搜索
    searchClick() {
      this.currentPage = 1;
      this.getUserData(this.currentPage, this.pageSize, this.search);
    },
    // 批量删除
    batchDelete() {
      this.$confirm("此操作将永久删除批量用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const batchDeleteData = this.$refs.table.selection;
          if (batchDeleteData.length == 0) {
            this.$message.warning("未选中任何信息！");
          }else{
            console.log(batchDeleteData);
            const {data : res} = await axios({
              method: 'DELETE',
              url: '/api/admin/batchDelete',
              data: batchDeleteData
            })
            if (res.code == 200) {
              this.$message.success("批量删除成功");
            }else if(res.code == 408){
              this.$message.warning("删除用户失败，请删除该用户其他数据后再删除用户");
            }else {
              this.$message.error("服务器错误，请稍后重试！");
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 单个删除
    deleteConfirm(scope) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await axios({
            method: "DELETE",
            url: "/api/admin/removeOne",
            params: {
              userId: scope.row.userId,
            },
          });
          if (res.code == 200) {
            this.$message.success("删除用户成功");
            this.getUserData(this.currentPage, this.pageSize, this.search);
          }else if(res.code == 408){
            this.$message.warning("删除用户失败，请删除该用户其他数据再删除该用户");
          }
           else {
            this.$message.error("服务器错误，请稍后重试！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 用户添加
    addAccount() {
      this.dialogTitle = "用户新增";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    // 用户编辑
    async accountEdit(scope) {
      this.dialogTitle = "用户编辑";
      this.dialogVisible = true;
      // 数据回显
      const { data: res } = await axios({
        method: "GET",
        url: "/api/admin/getUserById",
        params: {
          userId: scope.row.userId,
        },
      });
      if (res.code !== 200) {
        this.$message.error("数据回显失败，请稍后重试！");
      } else {
        console.log(res);
        // 数据回显
        this.userForm = {};
        this.userForm.userGender = parseInt(res.data.userGender);
        this.userForm.userId = res.data.userId;
        this.userForm.userIdentity = parseInt(res.data.userIdentity);
        this.userForm.userIdentityNumber = res.data.userIdentityNumber;
        this.userForm.userMobile = res.data.userMobile;
        this.userForm.userName = res.data.userName;
        this.userForm.userPassword = res.data.userPassword;
        // 给单选框回显
        // this.radioForIdentity = parseInt(res.data.userIdentity);
        // this.radioForGender = parseInt(res.data.userGender);
      }
    },
    // 点击确定
    confirmClick() {
      if (this.dialogTitle == "用户编辑") {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const { data: res } = await axios({
              method: "PUT",
              url: "/api/admin/update",
              data: this.userForm,
            });
            if (res.code == 200) {
              this.$message.success("更新用户数据成功");
              this.getUserData(this.currentPage, this.pageSize, this.search);
              this.dialogVisible = false;
            } else {
              this.$message.error("服务器错误，请稍后重试！");
            }
          } else {
            return;
          }
        });
      } else if (this.dialogTitle == "用户新增") {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const {data : res} = await axios({
              method: 'POST',
              url: '/api/admin/add',
              data: this.userForm
            })
            if (res.code == 200) {
              this.$message.success("新增成功");
              this.dialogVisible = false;
              this.getUserData(this.currentPage,this.pageSize,this.search);
            }else if(res.code == 408){
              this.$message.warning("用户存在，请检查！");
            }
            else{
              this.$message.error("服务器错误，请稍后重试！");
            }
          }else {
            return;
          }
        })
      }
    },
  },
};
</script>

<style>
/* 公共样式修改 */
.accountContainer {
  height: 100%;
  padding: 50px;
}
.accountContainer .el-card {
  margin-top: 0px;
  margin-right: 0px;
}
/* 处理表格间距 */
.accountContainer .el-card .el-row:nth-child(2) {
  margin-top: 30px;
}
/* 处理分页间距 */
.accountContainer .el-card .el-row:nth-child(3) {
  margin-top: 30px;
}
</style>